package com.leetcode;

import java.util.*;

public class 无重复最长字符串 {

    /**
     * 暴力循环 -- 刘学奇写的
     *
     * @param s
     * @return
     */
    public static int nopeatStr(String s) {
        if (s.length() == 0) return 0;
        int maxLen = 1;
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length - 1; i++) {
            String newStr = chars[i] + "";
            for (int j = i + 1; j < chars.length; j++) {
                if (newStr.indexOf(chars[j]) == -1) {
                    newStr = newStr + chars[j] + "";
                } else {
                    break;
                }
            }
            if (newStr.length() > maxLen) {
                maxLen = newStr.length();
            }
        }
        return maxLen;
    }


    /**
     * 使用滑动窗口  使用两个指针
     * https://www.cnblogs.com/huansky/p/13488234.html
     * @param s ...
     */
    public static int otherMethod(String s) {
        // 用来保存窗口中的元素
        HashSet<Character> characters = new HashSet<Character>();
        char[] chars = s.toCharArray();
        int len = chars.length;
        // rk为窗口的初始位置
        int maxLen = 0, rk = -1;
        for (int n = 0; n < len; n++) {
            if (n != 0) {
                characters.remove(chars[n - 1]);
            }
            while (rk + 1 < len && !characters.contains(chars[rk + 1])) {
                characters.add(chars[rk + 1]);
                ++rk;
            }
            maxLen = Math.max(maxLen, rk - n + 1);
        }
        return maxLen;
    }

    public static void main(String[] args) {
        System.out.println(otherMethod("abcabcbb"));
}

}
